package test.nettys.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author wangshaopeng
 * @Date 2021/8/3
 */
public class Nio12 {


    public static void main(String[] args) throws IOException {
        int[] ports = new int[5];

        ports[0] = 6000;
        ports[1] = 6001;
        ports[2] = 6002;
        ports[3] = 6003;
        ports[4] = 6004;

        Selector selector = Selector.open();
        for (int i = 0; i < ports.length; i++) {
            ServerSocketChannel socketChannel = ServerSocketChannel.open();

            socketChannel.configureBlocking(false);
            ServerSocket socket = socketChannel.socket();
            InetSocketAddress address = new InetSocketAddress(ports[i]);
            socket.bind(address);

            socketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("监听端口"+ports[i]);



        }

        while (true){
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();


            Iterator<SelectionKey> iterator = selectionKeys.iterator();


            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();

                if (selectionKey.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel accept = channel.accept();
                    accept.configureBlocking(false);
                    accept.register(selector, SelectionKey.OP_READ);


                    System.out.println("开启链接"+selectionKey);
                }else if(selectionKey.isReadable()){
                    SocketChannel channel = (SocketChannel) selectionKey.channel();


                    while (true){
                        ByteBuffer byteBuffer = ByteBuffer.allocate(100);
                        int byteNum = channel.read(byteBuffer);
                        if (byteNum<=0) {
                            break;
                        }
                        byteBuffer.flip();
                        channel.write(byteBuffer);

                        System.out.println("会写"+selectionKey);

                    }


                }



                iterator.remove();


            }





        }


    }
}
